package com.cdn.auth.context;

import com.cdn.auth.component.BeanComponent;
import com.cdn.auth.exception.BadCredentialsException;
import com.cdn.auth.exception.BeanNotFountException;
import com.cdn.auth.user.UserDetails;
import com.cdn.auth.user.UserDetailsService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 蔡定努
 * 2024/06/29 12:39
 */
public class UserAuthToken {

    private static final Log log = LogFactory.getLog(UserAuthToken.class);
    // 缓存 Bean 实例以提高性能
    private static UserDetailsService userDetailsService;
    private static TokenManager tokenManager;

    static {
        initBeans();
    }

    private static void initBeans() {
        try {
            userDetailsService = BeanComponent.getBean(UserDetailsService.class);
            tokenManager = BeanComponent.getBean(TokenManager.class);
        } catch (Exception e) {
            throw new BeanNotFountException("请在UserDetailsService子类中实现登录逻辑");
        }
    }


    public static String login(String username, String password) throws Exception{
        UserDetails userDetails = userDetailsService.login(username, password);
        if (userDetails == null) {
           throw new BadCredentialsException("用户名或密码错误");
        }
        return tokenManager.createToken(userDetails);
    }


    public static boolean logout() {
        return tokenManager.removeToken();
    }


}
